package com.itheima.d6_tcp3;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    static ArrayList<Socket> allClient = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(50);

        //创建服务端对象
        ServerSocket serverSocket = new ServerSocket(7788);
        //接受客户端连接
        while (true) {
            Socket socket = serverSocket.accept();//用来跟客户端进行交互
            allClient.add(socket);

            //用线程池去完成收数据任务
            threadPool.execute(new TalkingTask(socket));
        }
    }
}

class TalkingTask implements Runnable {
    private final Socket socket;

    public TalkingTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //获取输入流，读取客户端发送的数据
        try {
            InputStream netIn = socket.getInputStream();
            DataInputStream dataIn = new DataInputStream(netIn);
            while (true) {
                String msg = dataIn.readUTF();
                System.out.println("收到" + socket.getInetAddress() + "信息：" + msg);
                //让所有客户端能够看到信息，转发信息给其他客户端
                broadcastMsg(msg);
                if (msg.equals("886")) {
                    break;
                }
            }


        } catch (IOException e) {
            //e.printStackTrace();
            System.out.println(socket.getInetAddress()+"你出错啦！！");
        } finally {
            //从集合中删除该socket
            Server.allClient.remove(socket);
            //释放资源
            try {
                if (socket != null) {
                    System.out.println(socket.getInetAddress()+"下线");
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void broadcastMsg(String msg) {
        for (Socket client : Server.allClient) {
            try {
                //获取该客户端对象的输出流写数据
                DataOutputStream dataOut = new DataOutputStream(client.getOutputStream());
                dataOut.writeUTF(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}